package net.wangds.common.base.funcs;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
import java.util.function.*;

public interface Functions {

    Logger LOGGER = LoggerFactory.getLogger(Functions.class);

    static String nvl(String v){
        return v==null?"":v;
    }

    static <T> T nvl(T v, T defaultValue){
        return v==null?defaultValue:v;
    }

    static <T> T nvl(T v, Supplier<T> defaultFac){
        return v == null?defaultFac.get():v;
    }

    static String nvl(String value, String defaultValue){
        return StringUtils.isEmpty(StringUtils.trim(value))?defaultValue:value;
    }

    static <T> List<T> ofList(T ... elements){
        List<T> res = new ArrayList<>();
        if(elements!=null){
            for(T el:elements){
                res.add(el);
            }
        }
        return res;
    }

    static String concate(Iterable<? extends CharSequence> it){
        if(it==null){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        it.forEach(sb::append);
        return sb.toString();
    }

    static <T> void each(T[] array, Consumer<T> callback, BiConsumer<T, ? super Throwable> onError){
        if(array!=null&&callback!=null){
            for(T c:array){
                try{
                    callback.accept(c);
                }catch(Throwable e){
                    if(onError!=null){
                        onError.accept(c, e);
                    }
                }
            }
        }
    }

    /**
     * 从Map中根据key找到value.
     * <p>Map中不存在的时候，如果通过加载函数找到了，会添加到Map中.</p>
     * @param key 唯一key.
     * @param map 搜索目标map.
     * @param whenNotFound map中没有找到时的加载方法.
     * @param <K> key类型.
     * @param <T> 查找目标类型.
     * @return 结果.
     */
    static <K, T> Optional<T> findInMap(K key, Map<K,T> map, Function<K, T> whenNotFound) {
        if(map==null){
            if(whenNotFound!=null){
                return Optional.ofNullable(whenNotFound.apply(key));
            }else{
                return Optional.empty();
            }
        }

        T res = map.get(key);
        if(res!=null){
            return Optional.of(res);
        }

        if(whenNotFound!=null){
            T target = whenNotFound.apply(key);
            if(target!=null){
                map.put(key, target);
            }
            return Optional.ofNullable(target);
        }else{
            return Optional.empty();
        }

    }

    /**
     * 判断obj是否是目标类型，并执行对应方法.
     * @param obj 目标对象.
     * @param targetClass 目标类型.
     * @param onSuccess 对应方法.
     * @param <T> 检查类型.
     * @param <R> 返回值.
     * @return 执行结果.
     * <p>非正常情况返回null.</p>
     */
    @SuppressWarnings("unchecked")
    static <T,R> R withTypeCheck(Object obj, Class<T> targetClass, Function<T, R> onSuccess){
        if(onSuccess==null){
            return null;
        }
        if(obj==null){
            return onSuccess.apply(null);
        }
        if(targetClass==null){
            return onSuccess.apply((T)obj);
        }
        if(targetClass.isInstance(obj)){
            return onSuccess.apply((T)obj);
        }else{
            LoggerFactory.getLogger(Functions.class).info("无法通过类型检查:"+obj+","+targetClass.getName());
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    static <T> void withTypeCheck(Object obj, Class<T> targetClass, Consumer<T> onSuccess){
        if(onSuccess==null){
            return ;
        }
        if(obj==null){
            onSuccess.accept(null);
        }
        if(targetClass==null){
            onSuccess.accept((T)obj);
        }else {
            if (targetClass.isInstance(obj)) {
                onSuccess.accept((T) obj);
            }else{
                LoggerFactory.getLogger(Functions.class).info("无法通过类型检查:"+obj+","+targetClass.getName());
            }
        }
    }

    /**
     *
     * @param input 所有节点列表.
     * @param idGetter 获得元素id的方法.
     * @param parentIdGetter 获得父元素id的方法.
     * @param combine 装配父节点和子节点的函数.
     *                <p>第一个参数是父节点，第二个参数是子节点</p>
     * @param <I> ID字段类型.
     * @param <T> 树形节点父类.
     * @param <E> 树形节点叶子节点类型.
     * @return
     */
    static <I, T, E extends T> List<E> toTrees(List<E> input, Function<T, I> idGetter, Function<T, I> parentIdGetter,
                               BiFunction<T, T, T> combine){
        List<E> res = new ArrayList<>();

        Map<I, T> map = new HashMap<>();

        input.forEach(c->map.put(idGetter.apply(c),c));

        for (E c : input) {
            I pid = parentIdGetter.apply(c);
            if(pid==null || ( pid instanceof String && StringUtils.isBlank((String)pid)) ){
                res.add(c);
            }else{
                T p = map.get(pid);
                if(p==null) {
                    res.add(c);
                } else {
                    combine.apply(p, c);
                }
            }
        }

        return res;
    }

    static String thowable2String(Throwable th){
        if(th==null){
            return null;
        }
        try(
                ByteArrayOutputStream buff = new ByteArrayOutputStream();
                OutputStreamWriter ow=new OutputStreamWriter(buff);
                PrintWriter pw = new PrintWriter(ow)){
            th.printStackTrace(pw);
            pw.flush();
            return new String(buff.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }



    static void tryRun(Runnable task, int maxTryCount, Consumer<Exception> onException){
        if(task==null){
            return;
        }
        int cnt = 0;
        while(true) {
            try {
                task.run();
                break;
            }catch (Exception ex){
                if(onException!=null){
                    try {
                        onException.accept(ex);
                    }catch(Exception e){
                        LOGGER.warn(e.getLocalizedMessage(), e);
                    }
                }else{
                    LOGGER.warn(ex.getLocalizedMessage(), ex);
                }
            }finally {
                cnt++;
            }
            if(cnt>maxTryCount){
                break;
            }
        }
    }

}
